// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

// Implementation of casting to extension types
#include <nebula/compute/kernels/common_internal.h>
#include <nebula/compute/kernels/scalar_cast_internal.h>
#include <nebula/types/scalar.h>

namespace nebula {
namespace compute {
namespace internal {

namespace {
turbo::Status CastToExtension(KernelContext* ctx, const ExecSpan& batch, ExecResult* out) {
  const CastOptions& options = turbo::checked_cast<const CastState*>(ctx->state())->options;
  const auto& ext_ty = static_cast<const ExtensionType&>(*options.to_type.type);
  auto out_ty = ext_ty.storage_type();

  DKCHECK(batch[0].is_array());
  std::shared_ptr<Array> array = batch[0].array.to_array();

  // Try to prevent user errors by preventing casting between extensions w/
  // different storage types. Provide a tip on how to accomplish same outcome.
  std::shared_ptr<Array> result;
  if (array->type()->id() == Type::EXTENSION) {
    if (!array->type()->equals(out_ty)) {
      return turbo::failed_precondition_error("Casting from '" + array->type()->to_string() +
                               "' to different extension type '" + ext_ty.to_string() +
                               "' not permitted. One can first cast to the storage "
                               "type, then to the extension type.");
    }
    result = array;
  } else {
    TURBO_MOVE_OR_RAISE(result, Cast(*array, out_ty, options, ctx->exec_context()));
  }

  ExtensionArray extension(options.to_type.get_shared_ptr(), result);
  out->value = std::move(extension.data());
  return turbo::OkStatus();
}

std::shared_ptr<CastFunction> GetCastToExtension(std::string name) {
  auto func = std::make_shared<CastFunction>(std::move(name), Type::EXTENSION);
  for (Type::type in_ty : AllTypeIds()) {
    KCHECK_OK(func->add_kernel(in_ty, {InputType(in_ty)}, kOutputTargetType,
                              CastToExtension, NullHandling::COMPUTED_NO_PREALLOCATE,
                              MemAllocation::NO_PREALLOCATE));
  }
  return func;
}

};  // namespace

std::vector<std::shared_ptr<CastFunction>> GetExtensionCasts() {
  auto func = GetCastToExtension("cast_extension");
  return {func};
}

}  // namespace internal
}  // namespace compute
}  // namespace nebula
